package Fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.List;

import Database.SQLquery;
import barcode.code.nhat.iuhbarcode.Main_Action;
import barcode.code.nhat.iuhbarcode.R;

public class Table_Fragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public static Table_Fragment newInstance(int sectionNumber) {
        Table_Fragment fragment = new Table_Fragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public Table_Fragment() {
    }

    private SQLquery login;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_show, container, false);
        login = new SQLquery(getActivity());
        login = login.open();

        ListView l = (ListView) v.findViewById(R.id.list_table);
        List<String> per = login.get_table();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, per);
        l.setAdapter(adapter);
        l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String a = String.valueOf(parent.getItemAtPosition(position));
                showDownloadDialog(a);

            }
        });
        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((Main_Action) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
    }

    private void showDownloadDialog(final String table) {
        AlertDialog.Builder downloadDialog = new AlertDialog.Builder(getActivity());
        downloadDialog.setTitle("Drop table");
        downloadDialog.setMessage("Do you want to drop "+table+" ?");
        downloadDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                login.db.execSQL("DROP TABLE " + table);
            }
        });
        downloadDialog.setNegativeButton("No", null);
        downloadDialog.setCancelable(true);
        downloadDialog.show();
    }
}
